package com.birboot.core;

import com.birboot.http.HttpServletRequest;
import com.birboot.http.HttpServletResponse;
import org.w3c.dom.ls.LSOutput;

import javax.sound.sampled.Line;
import javax.swing.plaf.PanelUI;
import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.SplittableRandom;

public class ClientHandler  implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //2处理请求
            //获取请求的抽象路径
            String str = request.getUri();
            System.out.println(str);

            //处理请求
            //将解析请求的细节移动到request构造器中进行
            //3 发送响应
            File baseDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());

            //定位累加在路径下的static目录
            File staticDir = new File(baseDir, "static");

            File file = new File(staticDir, str);


            //判断若读到的文件不为空并且不为目录
            if (file.isFile()) {
              response.setContentFile(file);
            } else {
                response.setA(404);
                response.setStr1("NotFound");
                file = new File(staticDir, "404.html");
                response.setContentFile(file);
            }

            //3 发送响应
            response.response();

            /*
            v5的第一个此时目标：将static目录下的index.html页面发送给浏览器
            类加载路径
             */

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


